/**
 * GWT Kad : Kademlia implementation for GWT
 * Copyright (C) 2012  Pierrick HYMBERT, Paul-André MISTRAL, Florian ALEXANDRE
 * 
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 * 
 */
package org.kad.gwt.web.client.kademelia.inject;

import javax.inject.Inject;
import javax.inject.Named;
import javax.inject.Singleton;

import org.kad.gwt.web.client.kademelia.model.KadId;
import org.kad.gwt.web.client.kademelia.model.KadNode;
import org.kad.gwt.web.client.transport.http.GWTKadHttpAppletServerService;

import com.google.gwt.inject.client.AbstractGinModule;
import com.google.gwt.storage.client.Storage;
import com.google.inject.Provides;

/**
 * The KAD DI module.
 *
 * @author Pierrick HYMBERT &lt;pierrick [dot] hymbert [at] gmail [dot] com&gt;
 */
public class KadModule extends AbstractGinModule {
    /**
     * The key to recover the kad id of this client.
     */
    public static final String KAD_LOCAL_NODE = "gwt.kad.node.local";
    /**
     * The key to recover the kad id of this client.
     */
    public static final String KAD_LOCAL_NODE_ID = KAD_LOCAL_NODE + ".id";

    /**
     * {@inheritDoc}
     */
    @Override
    protected void configure() {
    }

    @Provides @Singleton @Named(KAD_LOCAL_NODE_ID) @Inject
    String providesLocalNodeKadIdString(Storage storage) {
        String kadId = storage.getItem(KAD_LOCAL_NODE_ID);
        if (kadId == null) {
            System.out.println("Generation de la clé ...");
            kadId = KadId.generateOne().toString();
            storage.setItem(KAD_LOCAL_NODE_ID, kadId);
        }
        System.out.println("Clé client " + kadId);
        return kadId;
    }

    @Provides @Singleton @Named(KAD_LOCAL_NODE_ID) @Inject
    KadId providesLocalNodeKadId(@Named(KAD_LOCAL_NODE_ID) String sKadId) {
        return new KadId(sKadId);
    }

    @Provides @Singleton @Named(KAD_LOCAL_NODE) @Inject
    KadNode providesLocalNode(@Named(KAD_LOCAL_NODE_ID) KadId kadId, GWTKadHttpAppletServerService httpAppletServerService) {
        return new KadNode(kadId, "127.0.0.1", httpAppletServerService.getServerListenPort());
    }
}
